//
//  BatteryViewController.m
//  BMS
//
//  Created by 颜魏 on 2024/12/9.
//

#import "BatteryViewController.h"
#import "CustomCircleView.h"
#import "BTManager.h"
#import "ProgressHUD.h"

@interface BatteryViewController ()

@property (weak, nonatomic) IBOutlet UILabel *socRateLabel;     //soc
@property (weak, nonatomic) IBOutlet UIView *socBgView;
@property (nonatomic, strong) CustomCircleView *circleView;
@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *bgViews;
@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *itemBgViews;

@property (weak, nonatomic) IBOutlet UILabel *voltageTitleLabel;    //电压
@property (weak, nonatomic) IBOutlet UILabel *voltageLabel;

@property (weak, nonatomic) IBOutlet UILabel *capacityTitleLabel;   //电容
@property (weak, nonatomic) IBOutlet UILabel *capacityLabel;

@property (weak, nonatomic) IBOutlet UILabel *healthTitleLabel;     //电池状态
@property (weak, nonatomic) IBOutlet UILabel *healthLabel;

@property (weak, nonatomic) IBOutlet UILabel *statusTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;

@property (nonatomic, assign) CGFloat    voltage;   //电压
@property (nonatomic, assign) CGFloat    capacity;  //电容

@end

@implementation BatteryViewController
{
    int preMOS, chgMOS, dsgMOS;
    int preRelay, mainRelay, dsgRelay, chgRelay;//充接Realy，主Realy，充电Realy，放电Relay
    int thirdSafeystatus, thirdSafeystatusSecondbyte;//三级保护信息
    int Vcell_0v, Vcell_UV, Vbat_0V, Vbat_UV, CHG_0C, DSG_0C, Cellchg_0T, Cellchg_UT,
            Celldsg_0T, Celldsg_UT, Vdelta_0p, Res, Tmos_OTP, SOC_low_p;
    int cbc_CHG, cbc_DSG;            //CBC_CHG异常标志,CBC_DSG异常标志
    float currentChg, currentDsg;//充电电流 放电电流
    float soc, soh;
    int differentialPressure;//压差
    float totalPressure;//总压
    float current;//电流
    float batteryLoopCount;//循环次数
    int AFE1, AFE2, CAN, EEPcommunicate, SPI, Upper, Client1, LCD, Wifi, BLE, APP, Directshort, EEPstorage, HSE, LSE, FLASH, BALANCE, ADC, HEAT, COOL;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];

    self.connectLabek.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap1:)];
    [self.connectLabek addGestureRecognizer:tap1];

    [self setLanguage];
    
    self.circleView = [[CustomCircleView alloc] initWithFrame:CGRectMake(0 , 0, 195, 195)];
    [self.socBgView addSubview:self.circleView];
}

- (void)handleTap1:(UITapGestureRecognizer *)tap {
    [[BTManager sharedBTManager] disconnectRootPeripheral];
}

- (IBAction)actionEdit:(id)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Modify bluetooth name", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *nameIntervalTextfield = alertController.textFields.firstObject;
        NSString *nameInterval = nameIntervalTextfield.text;
        if (nameInterval.length) {
            if (nameInterval.length > 16) {
                [ProgressHUD showErrorMessage:@"Bluetooth name cannot exceed 16 characters"];
                return;
            }
            nameInterval = [NSString stringWithFormat:@"AT+NAME=BT_%@,0", nameInterval];
            [[BTManager sharedBTManager] sendCommandModifyName:nameInterval];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[BTManager sharedBTManager] retartScan];
            });
        }
    }]];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = NSLocalizedString(@"Please enter the bluetooth name(16 characters)", nil);
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        label.text = @"BT_";
        label.font = [UIFont systemFontOfSize:14];
        textField.leftViewMode = UITextFieldViewModeAlways;
        textField.leftView = label;
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)setLanguage {
    self.voltageTitleLabel.text = NSLocalizedString(@"Voltage",nil);
    self.capacityTitleLabel.text = NSLocalizedString(@"Capacity",nil);
    self.healthTitleLabel.text = NSLocalizedString(@"Health",nil);
    self.statusTitleLabel.text = NSLocalizedString(@"Status",nil);
    self.healthLabel.text = NSLocalizedString(@"Perfect", nil);
    self.statusLabel.text = NSLocalizedString(@"Standby", nil);
}

- (void)updateUI {
    self.socRateLabel.text = [NSString stringWithFormat:@"%.1f", soc];
    self.circleView.rate = (NSInteger)soc;
    [self.circleView startAnimation];
    self.voltageLabel.text = [NSString stringWithFormat:@"%.2fV", self.voltage];
    self.capacityLabel.text = [NSString stringWithFormat:@"%.2fAh", self.capacity];

//    if (self.disChargingCurrent>0) {
//        self.healthLabel.text = NSLocalizedString(@"Discharging", nil);
//    } else if (self.chargingCurrent>0) {
//        self.healthLabel.text = NSLocalizedString(@"Charging", nil);
//    }else if (self.cbcDSG > 0 && (self.preMOS==0) && (self.chgMOS==0) && (self.dsgMOS==0) && (self.preRelay==0)&& (self.chgRelay==0)&&(self.dsgRelay==0)&&(self.mainRelay==0) ){
//        self.healthLabel.text = NSLocalizedString(@"Short\nCircuit", nil);
//    } else if (self.chargingExceed>0||self.disChargingExceed>0){
//        self.healthLabel.text = NSLocalizedString(@"Over\nCurrent", nil);
//    }else if (self.chargingTemperatureExceed>0||self.disChargingTemperatureExceed>0){
//        self.healthLabel.text = NSLocalizedString(@"Over\nTemperature", nil);
//    }else if (self.voltageSingleExceed>0||self.voltageTotalExceed>0){
//        self.healthLabel.text = NSLocalizedString(@"Over\nVoltage", nil);
//    }else if (self.voltageSingleLower>0||self.voltageTotalLower>0){
//        self.healthLabel.text = NSLocalizedString(@"Under\nVoltage", nil);
//    }else {
//        self.healthLabel.text = NSLocalizedString(@"Standby", nil);
//    }
//
//    if ((self.cbcDSG>0 && (self.preMOS==0) && (self.chgMOS==0) && (self.dsgMOS==0) && (self.preRelay==0) && (self.chgRelay==0) && (self.dsgRelay==0) && (self.mainRelay==0)) || (self.chargingExceed>0 || self.disChargingExceed>0) || (self.chargingTemperatureExceed>0 || self.disChargingTemperatureExceed>0) || (self.voltageSingleExceed>0 || self.voltageTotalExceed>0) || (self.voltageSingleLower>0 || self.voltageTotalLower>0)){
//        self.healthLabel.text = NSLocalizedString(@"Fault", nil);
//    } else {
//        self.healthLabel.text = NSLocalizedString(@"Perfect", nil);
//    }
    
    if (currentDsg>0) {
        self.statusLabel.text = NSLocalizedString(@"Discharging", nil);
    } else if (currentChg>0) {
        self.statusLabel.text = NSLocalizedString(@"Charging", nil);
    }else if (cbc_DSG > 0 &&  (preMOS==0) &&(chgMOS==0) && (dsgMOS==0) && (preRelay==0)&& (chgRelay==0)&&(dsgRelay==0)&&(mainRelay==0) ){
        self.statusLabel.text = NSLocalizedString(@"Short\nCircuit", nil);
    } else if (CHG_0C>0||DSG_0C>0){
        self.statusLabel.text = NSLocalizedString(@"Over\nCurrent", nil);
    }else if (Cellchg_0T>0||Celldsg_0T>0){
        self.statusLabel.text = NSLocalizedString(@"Over\nTemperature", nil);
    }else if (Vcell_0v>0||Vbat_0V>0||soc>=100){
        self.statusLabel.text = NSLocalizedString(@"Over\nVoltage", nil);
    }else if (Vcell_UV>0||Vbat_UV>0){
        self.statusLabel.text = NSLocalizedString(@"Under\nVoltage", nil);
    }else {
        self.statusLabel.text = NSLocalizedString(@"Standby", nil);
    }

//    if ((cbc_DSG > 0 &&  (preMOS==0) &&(chgMOS==0) && (dsgMOS==0) && (preRelay==0)&& (chgRelay==0)&&(dsgRelay==0)&&(mainRelay==0))||(CHG_0C>0||DSG_0C>0)||(Cellchg_0T>0||Celldsg_0T>0)||(Vcell_0v>0||Vbat_0V>0)
//    ||(Vcell_UV>0||Vbat_UV>0)){
//        self.healthLabel.text = NSLocalizedString(@"Fault", nil);
//    } else {
        self.healthLabel.text = NSLocalizedString(@"Perfect", nil);
//    }

}

#pragma mark - notification
- (void)didReciveData:(NSNotification *)notification {
    NSData *reciveData = notification.object;
    Byte *receieveData = (Byte*)reciveData.bytes;
//    if (dataBytes[2]==0x2a) {
//        //3.3 主控读取时钟及保护记录等信息
////        //AFE1异常标志
////        NSInteger afe1 = dataBytes[3+0x09*2];
////        //AFE2异常标志
////        NSInteger afe2 = dataBytes[3+0x09*2+1];
////        //EEP通讯异常标志
////        NSInteger eepCommunicate = dataBytes[3+0x0a*2+1];
////        //EEP存储异常标志
////        NSInteger eepStorage = dataBytes[3+0x0f*2];
//        //CBC_CHG异常标志
//        NSInteger cbcCHG = dataBytes[3+0x0e*2+1];
//        //CBC_DSG异常标志
//        self.cbcDSG = dataBytes[3+0x13*2];
//        if ((self.preMOS>0) | (self.chgMOS>0) | (self.dsgMOS>0) | (self.preRelay>0)| (self.chgRelay>0) | (self.dsgRelay>0) | (self.mainRelay>0)) {
//            self.cbcDSG = 0;
//            cbcCHG = 0;
//        }
////        NSInteger hardwareAlarm = afe1 + afe2 + eepCommunicate + eepStorage + self.cbcDSG + cbcCHG;
//    }
//    if (dataBytes[2]==0x18) {
//        //主机读取电池其他信息 3.4
//        NSInteger secondByte = dataBytes[4];
//        //预充MOS管
//        self.preMOS = (secondByte & 0x02) > 0 ? 1 : 0;
//        //充电MOS管
//        self.chgMOS = (secondByte & 0x04) > 0 ? 1 : 0;
//        //放电MOS管
//        self.dsgMOS = (secondByte & 0x08) > 0 ? 1 : 0;
//        //预充继电器
//        self.preRelay = (secondByte & 0x10) > 0 ? 1 : 0;
//        //分口充电继电器
//        self.chgRelay = (secondByte & 0x20) > 0 ? 1 : 0;
//        //分口放电继电器
//        self.dsgRelay = (secondByte & 0x40) > 0 ? 1 : 0;
//        //同口主继电器
//        self.mainRelay = (secondByte & 0x80) > 0 ? 1 : 0;
//    }
//    if ((dataBytes[2]==0x32) & (reciveData.length>30)) {
//        //3.2 主控读取电池温度电流等信息
//        self.soc = dataBytes[3+0x0e*2]*256 + dataBytes[3+0x0e*2+1];
//        self.capacity = dataBytes[3+0x10*2]*256 + dataBytes[3+0x10*2+1];
//        self.capacity = self.capacity/100.0;
//
//        //放电电流
//        self.disChargingCurrent = dataBytes[3+0xd*2]*256+dataBytes[3+0xd*2+1];
//        //充电电流
//        self.chargingCurrent = dataBytes[3+0xc*2]*256+dataBytes[3+0xc*2+1];
//
//        //三级保护信息
////        NSInteger thirdSafeystatus = dataBytes[3+0x16*2] & 0xff;
//        NSInteger thirdSafeystatusSecondbyte = dataBytes[3+0x16*2+1];
//        //单节过压
//        self.voltageSingleExceed = (thirdSafeystatusSecondbyte & 0x01) > 0 ? 1 : 0;
//        //单节欠压
//        self.voltageSingleLower = (thirdSafeystatusSecondbyte & 0x02) > 0 ? 1 : 0;
//        //总压过压
//        self.voltageTotalExceed = (thirdSafeystatusSecondbyte & 0x04) > 0 ? 1 : 0;
//        //总压欠压
//        self.voltageTotalLower = (thirdSafeystatusSecondbyte & 0x08) > 0 ? 1 : 0;
//        //充电过流
//        self.chargingExceed = (thirdSafeystatusSecondbyte & 0x10) > 0 ? 1 : 0;
//        //放电过流
//        self.disChargingExceed = (thirdSafeystatusSecondbyte & 0x20) > 0 ? 1 : 0;
//        //充电过温
//        self.chargingTemperatureExceed = (thirdSafeystatusSecondbyte & 0x40) > 0 ? 1 : 0;
//        //放电过温
//        self.disChargingTemperatureExceed = (thirdSafeystatusSecondbyte & 0x80) > 0 ? 1 : 0;
////        //充电低温
////        NSInteger chargingTemperatureLower = (thirdSafeystatus & 0x01) > 0 ? 1 : 0;
////        //放电低温
////        NSInteger disChargingTemperatureLower = (thirdSafeystatus & 0x02) > 0 ? 1 : 0;
////        //压差过大
////        NSInteger voltageDifferenceExceed = (thirdSafeystatus & 0x04) > 0 ? 1 : 0;
//    }
    
    if (receieveData[2]==0x4c) {
        //3.1 主控读取电池电压数据
        self.voltage = (float)(receieveData[3+0x25*2]*256+receieveData[3+0x25*2+1]);
        self.voltage = (self.voltage * 10) / 1000.0;
    }

    //3.2 主控读取电池温度电流等信息
    if ((receieveData[2] == 0x32) & (reciveData.length > 30)) {

//        float tHigh = receieveData[3 + 0x0a * 2] * 256 + receieveData[3 + 0x0a * 2 + 1];
//        batteryHighTemperature = (tHigh - 400) / 10; //最高温度

        currentChg = (float) ((receieveData[3 + 0xc * 2] * 256 + receieveData[3 + 0xc * 2 + 1])) / 10.0f;
        currentDsg = (float) ((receieveData[3 + 0xd * 2] * 256 + receieveData[3 + 0xd * 2 + 1])) / 10.0f;
        current = currentDsg;
        if (currentChg > 0) current = currentChg;

        batteryLoopCount = receieveData[3 + 0x13 * 2] * 256 + receieveData[3 + 0x13 * 2 + 1];
        
        soc = receieveData[3 + 0x0e * 2] * 256 + receieveData[3 + 0x0e * 2 + 1]; //SOC
        soh = receieveData[3 + 0x0e * 2 + 2] * 256 + receieveData[3 + 0x0e * 2 + 3]; //SOH
        
        //剩余mAH
        self.capacity = receieveData[3 + 0x10 * 2] * 256 + receieveData[3 + 0x10 * 2 + 1];
        self.capacity = self.capacity/100.0;

//        thirdSafeystatus=receieveData[3+0x16*2];
        thirdSafeystatusSecondbyte=receieveData[3+0x16*2+1];
        Vcell_0v = (thirdSafeystatusSecondbyte & 0x01) > 0 ? 1 : 0;//单节过压
        Vcell_UV = (thirdSafeystatusSecondbyte & 0x02) > 0 ? 1 : 0;//单节欠压
        Vbat_0V = (thirdSafeystatusSecondbyte & 0x04) > 0 ? 1 : 0;//总压过压
        Vbat_UV = (thirdSafeystatusSecondbyte & 0x08) > 0 ? 1 : 0;//总压欠压
        CHG_0C = (thirdSafeystatusSecondbyte & 0x10) > 0 ? 1 : 0;//充电过流
        DSG_0C = (thirdSafeystatusSecondbyte & 0x20) > 0 ? 1 : 0;//放电过流
        Cellchg_0T = (thirdSafeystatusSecondbyte & 0x40) > 0 ? 1 : 0;//充电过温
        Celldsg_0T = (thirdSafeystatusSecondbyte & 0x80) > 0 ? 1 : 0;//放电过温

        [[NSNotificationCenter defaultCenter] postNotificationName:kBTSOCData object:@(Vcell_0v>0||Vbat_0V>0)];

        
//        Cellchg_UT = (thirdSafeystatus & 0x01) > 0 ? 1 : 0;//充电低温
//        Celldsg_UT = (thirdSafeystatus & 0x02) > 0 ? 1 : 0;//放电低温
//        Vdelta_0p = (thirdSafeystatus & 0x04) > 0 ? 1 : 0;//压差过大
//        SOC_low_p = (thirdSafeystatus & 0x10) > 0 ? 1 : 0;//soc过低
//        Tmos_OTP = (thirdSafeystatus & 0x20) > 0 ? 1 : 0;//mos过温
    }


    if ((receieveData[2] == 0x2a) & (reciveData.length > (3 + 0x03 * 2 + 11))) //3.3 主控读取时钟及保护记录等信息
    {
        AFE1 = receieveData[3 + 0x09 * 2];
        AFE2 = receieveData[3 + 0x09 * 2 + 1];
        CAN = receieveData[3 + 0x0a * 2];
        EEPcommunicate = receieveData[3 + 0x0a * 2 + 1];
        SPI = receieveData[3 + 0x0b * 2];
        Upper = receieveData[3 + 0x0b * 2 + 1];
        Client1 = receieveData[3 + 0x0c * 2];
        LCD = receieveData[3 + 0x0c * 2 + 1];
        Wifi = receieveData[3 + 0x0d * 2];
        BLE = receieveData[3 + 0x0d * 2 + 1];
        APP = receieveData[3 + 0x0e * 2];
        EEPstorage = receieveData[3 + 0x0f * 2];
        HSE = receieveData[3 + 0x0f * 2 + 1];
        LSE = receieveData[3 + 0x10 * 2];
        FLASH = receieveData[3 + 0x10 * 2 + 1];
        BALANCE = receieveData[3 + 0x11 * 2];
        ADC = receieveData[3 + 0x11 * 2 + 1];
        HEAT = receieveData[3 + 0x12 * 2];
        COOL = receieveData[3 + 0x12 * 2 + 1];
        cbc_CHG = receieveData[3 + 0x0e * 2 + 1];
        cbc_DSG = receieveData[3 + 0x13 * 2];
        if ((preMOS > 0) | (chgMOS > 0) | (dsgMOS > 0) | (preRelay > 0) | (chgRelay > 0) | (dsgRelay > 0) | (mainRelay > 0)) {
            cbc_CHG = 0;
            cbc_DSG = 0;
        }
    }
    //主机读取电池其他信息 3.4
    if (receieveData[2] == 0x18) {
        int firstByte, secondByte;
        firstByte = receieveData[3];
        secondByte = receieveData[4];
        secondByte=secondByte&0xff;
//        startUp = (secondByte & 0x01) > 0 ? 1 : 0;
        preMOS = (secondByte & 0x02) > 0 ? 1 : 0;
        chgMOS = (secondByte & 0x04) > 0 ? 1 : 0;
        dsgMOS = (secondByte & 0x08) > 0 ? 1 : 0;
        preRelay = (secondByte & 0x10) > 0 ? 1 : 0;
        chgRelay = (secondByte & 0x20) > 0 ? 1 : 0;
        dsgRelay = (secondByte & 0x40) > 0 ? 1 : 0;
        mainRelay = (secondByte & 0x80) > 0 ? 1 : 0;
//        if ((preMOS + chgMOS + dsgMOS) > 0) {
//            if (isRelayMode == 1) {
//                isRelayMode = 0;
//            }
//            isRelayMode = 0;
//        } else {
//            if (isRelayMode == 0) {
//                isRelayMode = 1;
//            }
//            isRelayMode = 1;
//        }
    }
    
    [self updateUI];
}


@end
